package com.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.util.Log;

import com.common.method.ChatHelper;

/**
 * 
 * @ClassName:VoiceSaveThread
 * @Description:TODO聊天voice
 * @author zhuw
 * @date 2013-8-19 下午9:15:04
 */
public class VoiceSaveThread extends Thread {
	String tag = "VoiceSaveThread";
	private List<String> voiceList = new ArrayList<String>();

	public VoiceSaveThread(List<String> voiceList) {
		this.voiceList = voiceList;
	}

	public VoiceSaveThread(String voiceUrl) {
		this.voiceList.add(voiceUrl);
	}

	@Override
	public void run() {
		if (voiceList != null && voiceList.size() > 0) {
			for (String voicdUrlPath : voiceList) {
				String fileName = voicdUrlPath.substring(voicdUrlPath
						.lastIndexOf("/") + 1);
				FileOutputStream fos = null;
				try {
					File file = new File(ChatHelper.getVoiceSavePath(),
							fileName);
					if (file.exists()) {
						Log.d(tag, "已经下载-------------->" + voicdUrlPath);
					} else {
						fos = new FileOutputStream(file);
						URL myFileUrl = new URL(voicdUrlPath);
						HttpURLConnection conn = (HttpURLConnection) myFileUrl
								.openConnection();
						conn.setDoInput(true);
						conn.setRequestMethod("GET");
						conn.setConnectTimeout(5000);
						conn.connect();
						InputStream in = conn.getInputStream();

						byte[] buffer = new byte[1024];
						int len1 = 0;

						while ((len1 = in.read(buffer)) > 0) {
							fos.write(buffer, 0, len1);
						}
						fos.flush();
						Log.d(voicdUrlPath, "下载voice成功..." + voicdUrlPath);
					}
				} catch (Exception e) {
					Log.d(voicdUrlPath, "下载voice错误..." + e.getMessage());
					e.printStackTrace();
				} finally {
					if (fos != null) {
						try {
							fos.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}

			}
		}
	}
}